package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.*;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: 商品
 * @author: xxx
 * @create: 2021/7/19 09:30
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderService service;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GetCreditsService getCreditsService;
    @Autowired
    private CommissionService commissionService;
    /**
     * @description: 确认订单
     * @param map
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/11 15:49
     */
    /**
     * @param map
     * @description: 确认订单
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/11 15:49
     */
    @RequestMapping("confirmOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result confirmOrder(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapOrder = service.getById(map);
        if (!mapOrder.get("status").toString().equals("3") && !mapOrder.get("status").toString().equals("4")) {
            map.put("status", 3);
            // 修改商品状态
            service.update(map);
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", mapOrder.get("goodsId"));
            mapNew.put("buyPrice", mapOrder.get("price"));
            mapNew.put("buyTime", mapOrder.get("createDate"));
            mapNew.put("uId", mapOrder.get("buyerId"));
            mapNew.put("added", 2);
            // 修改订单状态为完成
            goodsService.update(mapNew);
            // 订单交易完成后，给介绍人0.5%的积分 --- new
            Map<String, Object> yqrUser = new HashMap<>();
            yqrUser.put("id", mapOrder.get("buyerId"));
            // 根据id查询当前用户信息
            Map<String, Object> meData = userService.getById(yqrUser);
            // 如果这个人有邀请人 就给邀请人 0.5% 的提成  [超级账号是”“空字符串]
            String Pid = (String) meData.get("pid");
            if (Pid.length() > 0) {
                Map<String, Object> mapPid = new HashMap<>();
                mapPid.put("pid", meData.get("pid"));
                // 根据pid查出用户的邀请人
                Map<String, Object> uData = userService.getByPid(mapPid);
                // 计算提成积分0.5% 积分
                BigDecimal money = new BigDecimal(Double.valueOf(mapOrder.get("price").toString()));//交易金额
                BigDecimal td = new BigDecimal(Double.valueOf(0.005));//提点
                BigDecimal tdMoney = money.multiply(td).setScale(2, BigDecimal.ROUND_HALF_UP);//乘法四舍五入保留两位小数
                // 获取用户积分
                Map<String, Object> params = new HashMap();
                params.put("id", uData.get("id"));
                Map<String, Object> UserCredits = getCreditsService.getMyCredits(params);
                // 计算剩余积分 原本积分+提成积分
                BigDecimal total = new BigDecimal(Double.valueOf(UserCredits.get("total").toString()));  // 账户目前可用积分 total
                BigDecimal tcMoney = total.add(tdMoney).setScale(2, BigDecimal.ROUND_HALF_UP);// 加法四舍五入保留两位小数
                // 存储积分信息
                Map<String, Object> creditMap = new HashMap<>();
                creditMap.put("id", IDTool.getUUID32());
                creditMap.put("userId", uData.get("id")); // 用户id
                creditMap.put("userName", uData.get("nikeName")); // 邀请人昵称
                creditMap.put("userPhone", uData.get("name"));  // 邀请人账号
                creditMap.put("putawayShopName", mapOrder.get("goodsName")); // 商品名称
                creditMap.put("putawayShopPrice", mapOrder.get("price"));    // 商品价格
                creditMap.put("putawayShopSn", mapOrder.get("orderSn"));  // 商品订单
                creditMap.put("getCredits", tdMoney); // 此单获得积分
                creditMap.put("accountCredits", tcMoney); // 账户剩余积分
                getCreditsService.saveInviteAdd(creditMap);
            }
            // 更新商品状态为已出售
            Map<String, Object> mapEarnings = new HashMap<>();
            mapEarnings.put("goodsId", mapOrder.get("goodsId"));
            mapEarnings.put("userId", mapOrder.get("userId"));
            mapEarnings.put("status", 2);
            mapEarnings.put("payStatus", 1);
            mapEarnings.put("payStatusNew", 2);
            goodsService.updateGoodsAddedEarnings(mapEarnings);

            return ResultUtil.success();
        } else {
            return ResultUtil.error(-500, "订单已完成,请勿重复操作");
        }
    }

    /**
     * @param map
     * @description: 取消订单
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/12 17:13
     */
    @RequestMapping("cancelOrder")
    public Result cancelOrder(@RequestBody Map<String, Object> map) {
        Map<String, Object> mapOrder = service.getById(map);
        if (mapOrder.get("status").toString().equals("1") ||
                mapOrder.get("status").toString().equals("2")) {
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", mapOrder.get("id"));
            mapNew.put("status", "4");
            mapNew.put("goodsId", mapOrder.get("goodsId"));
            service.update(mapNew);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-500, "该状态不允许取消订单");
        }
    }

    /**
     * @param map
     * @description: 确认提现
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/11 15:52
     */
    @RequestMapping("confirmWithdraw")
    @Transactional(rollbackFor = Exception.class)
    public Result confirmWithdraw(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapWithdraw = commissionService.getWithdrawById(map);
        if (TokenTool.getPermissionType().equals("t")) {
            map.put("status", 2);
            if (mapWithdraw.get("status").toString().equals("1")) {
                commissionService.updateWithdraw(map);
                BigDecimal money = new BigDecimal(Double.valueOf(mapWithdraw.get("money").toString()));//提现金额
                Map<String, Object> mapCommission = new HashMap<>();
                mapCommission.put("id", mapWithdraw.get("userId"));
                Map<String, Object> commission = commissionService.getById(mapCommission);
                Double commissionMoney = Double.parseDouble(commission.get("money").toString());
                Double commissionOldMoney = Double.parseDouble(commission.get("oldMoney").toString());
                mapCommission.put("money", new BigDecimal(commissionMoney).subtract(money).setScale(2, BigDecimal.ROUND_HALF_UP));
                mapCommission.put("oldMoney", new BigDecimal(commissionOldMoney).add(money).setScale(2, BigDecimal.ROUND_HALF_UP));
                mapCommission.put("uuid", commission.get("uuid"));
                mapCommission.put("uuidNew", IDTool.getUUID32());
                Integer result = commissionService.update(mapCommission);
                if (result <= 0) {
                    throw new Exception("更新失败");
                }
            } else {
                return ResultUtil.error(-500, "该状态不允许修改");
            }
        }
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 取消提现
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/13 11:34
     */
    @RequestMapping("cancelWithdraw")
    public Result cancelWithdraw(@RequestBody Map<String, Object> map) {

        Map<String, Object> mapWithdraw = commissionService.getWithdrawById(map);
        if (TokenTool.getPermissionType().equals("t")) {
            map.put("status", 3);
            if (mapWithdraw.get("status").toString().equals("1")) {
                commissionService.updateWithdraw(map);
            } else {
                ResultUtil.error(-500, "该状态不允许取消");
            }
        }
        return ResultUtil.success();
    }

    /**
     * @param json
     * @description: 分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getPage")
    public Result getPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        if (TokenTool.getPermissionType().equals("t")) {
            jsonObject.put("hszStudioIds", TokenTool.getHszStudioId());
        }
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getList(jsonObject);
        int total = service.getCount(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param json
     * @description: 列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getList")
    public Result getList(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        if (TokenTool.getPermissionType().equals("t")) {
            jsonObject.put("hszStudioIds", TokenTool.getHszStudioId());
        }
        return ResultUtil.success(service.getList(jsonObject));
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getById")
    public Result getById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getById(map));
    }

    /**
     * @param json
     * @description: 分页每天的成交流水总和
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getOrderCount")
    public Result getOrderCount(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getOrderCount(jsonObject);
        int total = service.getOrderCounts(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    @RequestMapping("delete")
    public Result delete(@RequestBody Map<String, Object> map) {
        service.delete(map);
        return ResultUtil.success();
    }
}
